﻿using System;
using System.IO;
using System.Threading.Tasks;
using Blackvon.SDK.Tencent.QCloud;
using COSXML.CosException;
using WPFNote.Utilities.Common;

namespace WPFNote.Utilities.Cloud;

public class TencentCloud
{
    public async Task<string> UploadFile(string userName, string filePath)
    {
        try
        {
            var fileName = Path.GetFileName(filePath);
            var cosKey = Config.Init().TencentCloudParam.TencentQCloudFolder + userName + "/" + fileName;
            var res =
                await new CosHelper(Config.Init().TencentCloudParam.Bucket,
                    Config.Init().TencentCloudParam.SecretId, Config.Init().TencentCloudParam.SecretKey,
                    Config.Init().TencentCloudParam.Region).PutObject(cosKey,
                    filePath);
            if (!res.Contains("200 OK"))
            {
                return string.Empty;
            }

            var fileUrl = Config.Init().TencentCloudParam.TencentQCloudBaseUrl + cosKey;
            return fileUrl;
        }
        catch
        {
            return string.Empty;
        }
    }
    
    public async Task<bool> DownloadFile(string userName, string filePath)
    {
        try
        {
            var fileName = Path.GetFileName(filePath);
            var fileFolder = Path.GetDirectoryName(filePath);
            var cosKey = Config.Init().TencentCloudParam.TencentQCloudFolder + userName + "/" + AppSession.ZipFileName;
            var res =
                await new CosHelper(Config.Init().TencentCloudParam.Bucket,
                    Config.Init().TencentCloudParam.SecretId, Config.Init().TencentCloudParam.SecretKey,
                    Config.Init().TencentCloudParam.Region).GetObject(cosKey,
                    fileFolder, fileName);
            if (!res.Contains("206 Partial Content"))
            {
                return false;
            }

            return true;
        }
        catch(CosServerException ex)
        {
            return false;
        }
        catch(Exception ex)
        {
            return false;
        }
    }
}